<template>
	<view class="">
		<h-watermark :title="departText" :mobile="nameText" :appName="numberText"></h-watermark>
		<view class="preview">
			<iframe :src="previewUrl" width="100%" frameborder="0" id="iframes"></iframe>
			<!-- <web-view :src="previewUrl"/> -->
			<u-action-sheet
				:actions="list"
				@select="handleDownload"
				@close="actionShow = false"
				:show="actionShow"
				closeOnClickOverlay
				safeAreaInsetBottom
			></u-action-sheet>
			<u-empty mode="data" icon="/static/empty/data.png" v-if="isError" text="传入格式不正确"></u-empty>
		</view>
	</view>
</template>
<script>
import { ONLINE_BASE_URL } from '@/utils/baseUrl.js'
import { encode } from '@/utils/base64.js'
export default {
	data() {
		return {
			previewUrl: '',
			isError: false,
			actionShow: false, // 操作按钮开关
			list: [{
				name: '下载',
				fontSize: '16',
			}],
			dUrl: '',
			navBarHeight: 0,
			bucketNamePrefix: false,
			watermarkTxt: '',
			departText: '',
			nameText: '',
			numberText: ''
		}
	},
	onLoad(options) {
		// #ifdef APP-PLUS
		const currentWebview = this.$scope.$getAppWebview() //获取当前页面的webview对象
		setTimeout(()=> {
			let wv = currentWebview.children()[0]
			wv.setStyle({scalable:true})
		}, 1000); //初始化调用时，需要延时一下
		// #endif
		this.bucketNamePrefix = options.bucketNamePrefix?options.bucketNamePrefix:''
		this.watermarkTxt = options.watermarkTxt?options.watermarkTxt:''
		// 单独处理该水印数据
		var textArrList = this.watermarkTxt? this.watermarkTxt.split('-') : []
		if (textArrList && textArrList.length) {
			this.departText = textArrList[0]? textArrList[0] : ''
			this.nameText = textArrList[1]? textArrList[1] : ''
			this.numberText = textArrList[2]? textArrList[2] : ''
		}
		this.dUrl = decodeURIComponent(options.url)
		let exit = this.dUrl.split('.').pop()
		const docArr = ['pptx', 'ppt', 'docx', 'doc', 'xlsx', 'xls', 'pdf','mp4']
		const imgArr = ['gif','jpg','jpeg','png','svg','GIF','JPG','JPEG','PNG','SVG','webp']
		// this.previewUrl = `https://view.xdocin.com/view?src=${encodeURIComponent(this.dUrl)}`
		if(this.bucketNamePrefix){
			this.previewUrl = ONLINE_BASE_URL + '?url=' + encodeURIComponent(encode(this.dUrl+`?bucketNamePrefix=${this.bucketNamePrefix}`))
		} else {
			this.previewUrl = ONLINE_BASE_URL + '?url=' + encodeURIComponent(encode(this.dUrl))
		}
		
		// if(docArr.indexOf(exit) > -1){
		// 	// this.previewUrl = ONLINE_BASE_URL + '?url=' + encodeURIComponent(encode(this.dUrl))
		// 	this.previewUrl = `https://view.xdocin.com/view?src=${encodeURIComponent(this.dUrl)}`
		// 	this.imgUrl = ''
		// }
		// if(imgArr.indexOf(exit) > -1){
		// 	this.imgUrl = this.dUrl
		// }
		if(docArr.indexOf(exit) == -1 && imgArr.indexOf(exit) == -1){
			this.previewUrl = ''
			this.isError = true
		} else {
			this.isError = false
		}
	},
	onReady() {
		let view = uni.createSelectorQuery().select(".nav-bar");
		view.boundingClientRect(data => {
			this.navBarHeight = data?.height || 0; // 导航栏的高度
		}).exec();
	},
	methods: {
		// uniapp 原生api -- uni.downloadFile下载
		handleDownLoad(url){
			uni.downloadFile({
				url: url,
				success: (result) => {
					if (result.statusCode === 200) {
						//文件保存到本地
						uni.saveFile({
							tempFilePath: result.tempFilePath, //临时路径
							success: function(ress) {
								uni.showToast({
									icon: 'none',
									mask: true,
									title: '文件已保存：' + ress.savedFilePath, //保存路径
									duration: 3000,
								});
							}
						});
					}
				},
				fail: (err) => {
					uni.showToast({
						icon: 'none',
						mask: true,
						title: '失败请重新下载',
					});
				}
			})
		},
		// H5+API定义的应用沙盒里的plus.downloader下载
		downLoadApp(url){
			let name = url.split('static/').pop()
			if(name.indexOf('?') > -1){
				name = name.substring(0,name.indexOf('?'))
			}
			let dtask = plus.downloader.createDownload(url,{
				//1.本地路径开头使用file://;
				//2.Android平台本地绝对路径为"storage/emulated/0",就是用户文件管理器能看到的了;
				//3.创建"xxx"作为文件夹名称，后缀是用于文件命名和格式修改，大家可以使用变量。
				filename: '_downloads/' + name //利用保存路径，实现下载文件的重命名
				},function(d, status) {//d为下载的文件对象;status下载状态
					if (status == 200) {//下载成功
						//d.filename是文件在保存在本地的相对路径，使用下面的API可转为平台绝对路径
						// let fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
						// plus.runtime.openFile(d.filename); //选择软件打开文件
						uni.showToast({
							icon: 'none',
							mask: true,
							title: '文件已保存：'+ d.filename, //保存路径
							duration: 3000,
						});
					} else {//下载失败
						uni.showToast({
							icon: 'none',
							title: '下载失败',
							mask: true,
							duration: 2000,
						});
						plus.downloader.clear(); //清除下载任务
					}
				}
			);
			dtask.start();//启用
		},
		handleDownload(index){
			let url = ''
			if(this.bucketNamePrefix){
				url = this.dUrl+`?bucketNamePrefix=${this.bucketNamePrefix}`
			} else {
				url = this.dUrl
			}
			// #ifndef APP-PLUS
				this.handleDownLoad(url)
			// #endif
			// #ifdef APP-PLUS
				this.downLoadApp(url)
			// #endif
		},
	},
}
</script>
<style lang="scss" scoped>
.preview {
	width: 100vw;
	height: 100vh;
	background-color: #fff;
	#iframes {
		height: 100%;
	}
	#p_video{
		width: 100%;
	}
	#p_img{
		width: 100%;
	}
}
</style>
